using UnityEngine;
using System.Collections.Generic;
using System.IO;

public static class TransformExtensions
{
	public static Transform FindRecursively( this Transform tf, string name )
	{
		if ( tf.name.Equals( name ) )
			return tf;

		foreach ( Transform child in tf )
		{
			Transform result = FindRecursively( child, name );
			if ( result != null )
				return result;
		}

		return null;
	}

	public static void DestroyAllChildren( this Transform tf )
	{
		List<GameObject> children = new List<GameObject>();
		foreach ( Transform child in tf )
			children.Add( child.gameObject );
		foreach ( GameObject go in children )
			GameObject.DestroyImmediate( go );
	}

	public static List<string> RelativePathList( this Transform root, bool deep, string parentPath = "", bool lowercase = false )
	{
		List<string> relpaths = new List<string>();
		
		foreach ( Transform child in root )
		{
			relpaths.Add( parentPath + child.name );

			if ( deep )
			{
				List<string> childlist = RelativePathList( child, deep, parentPath + child.name + "/", lowercase );
				relpaths.AddRange( childlist );
			}
		}

		return relpaths;
	}

	public static Dictionary<string, string> RelativePathDict( this Transform root, bool deep, string parentPath = "", bool lowercase = false )
	{
		List<string> list = RelativePathList( root, deep, parentPath, lowercase );
		Dictionary<string, string> dict = new Dictionary<string, string>();
		foreach ( string path in list )
		{
			string name = Path.GetFileNameWithoutExtension( path );
			if ( lowercase )
				name = name.ToLower();
			dict[ name ] = path;
		}

		return dict;
	}

	public static Bounds HierarchyBounds( this Transform root )
	{
		Bounds b = new Bounds( root.position, Vector3.zero );

		foreach ( Transform child in root )
		{
			Bounds childBounds = HierarchyBounds( child );
			b.Encapsulate( childBounds );
		}

		if ( root.renderer != null )
			b.Encapsulate( root.renderer.bounds );

		return b;
	}
}